package com.hxht.cmp.service.impl;

import com.hxht.cmp.common.Constants;
import com.hxht.cmp.entity.CourtRoom;
import com.hxht.cmp.entity.Plan;
import com.hxht.cmp.entity.Trial;
import com.hxht.cmp.entity.Video;
import com.hxht.cmp.mapper.PlanMapper;
import com.hxht.cmp.mapper.TrialMapper;
import com.hxht.cmp.mapper.VideoMapper;
import com.hxht.cmp.service.CaseVideoService;
import com.hxht.cmp.utils.Ftp;
import com.hxht.cmp.utils.http.HttpClientRequest;
import com.hxht.cmp.utils.http.HttpClientResponse;
import com.hxht.cmp.utils.http.HttpClientUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToTextConverter;
import org.apache.poi.hwpf.usermodel.HeaderStories;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.*;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CaseVideoServiceImpl implements CaseVideoService {
    final Logger logger = LoggerFactory.getLogger(CaseVideoServiceImpl.class);
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private TrialMapper trialMapper;

    @Override
    public List<Video> selectPlayVideo(String trialUid) {
        Example example = new Example(Video.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("trialUid", trialUid);
        example.setOrderByClause("chn asc,start_rec_time asc");
        List<Video> videos = videoMapper.selectByExample(example);
        return videos;
    }

    @Override
    public List<String> courtrecForId(String trialUid, String courtUid) {
        String note = null;
        Trial trial = new Trial();
        trial.setUid(trialUid);
        trial = trialMapper.selectOne(trial);
        if (null == trial) {
            return null;
        }
        if (null == trial.getCourtrec()) {
            return null;
        }
        Plan plan = new Plan();
        plan.setUid(trial.getPlanUid());
        if (null == plan) {
            return null;
        }
        List<String> list = new ArrayList<>();
        String noteUrl = "";
        try {
            //处理下ftp,换成http下载,原本为http则不变
            StringBuilder s = new StringBuilder(trial.getCourtrec());
            StringBuilder s1 = null;
            if (s.toString().startsWith("ftp") || s.toString().startsWith("FTP")) {
                StringBuilder head = new StringBuilder(s.substring(0, s.indexOf("/", 8)));
                StringBuilder suffer = new StringBuilder(s.substring(s.indexOf("/", 8)));
                s1 = new StringBuilder((head + ":8200" + suffer).replace("ftp", "http"));
            } else {
                s1 = s;
            }

            //笔录最后的下载地址--http://205.73.4.100:8200/movies1/8e822937d14940d9801be42933b3ca62/TheRecord_new.doc
            logger.info("笔录下载地址:" + s1.toString());
            noteUrl = s1.toString();

            if (null == trial.getCourtrec()) {
                note = "暂时没有笔录文件！";
            } else {
                String filePath = trial.getCourtrec();
                String courtroomUid = plan.getCourtRoomUid();
                if (filePath == null || "".equals(filePath)) {
                    logger.warn("WARN: 需要加载笔录不存在");
                    note = "需要查阅的笔录不存在！";
                }
                InputStream in = new URL(s1.toString()).openStream();
                note = getWordText(in, null);
            }
        } catch (Exception e) {
            note = "笔录信息异常！";
            logger.error("FATAL: 笔录错误" + e.getMessage());
        }
        //封装下

        list.add(note);
        list.add(noteUrl);
        //返回笔录路劲
        return list;
    }

    @Override
    public Video getVideoInfoByChn(Map<String, Object> map) {
        return videoMapper.getVideoInfoByChn(map);
    }

    @Override
    public List<Trial> getTrialsByPlanUid(String planUid) {
        Trial trial = new Trial();
        trial.setPlanUid(planUid);
        trial.setActive(1);
        return trialMapper.select(trial);
    }

    /**
     * 通过jni调用本地c库
     *
     * @param ftpFileName
     * @param localPath
     * @param courtroomUid 法庭uid
     * @throws SQLException
     */
    private void ftp(String ftpFileName, String localPath, String courtroomUid) {
        try {
            //庭审法庭信息取得
            CourtRoom courtRoom = Constants.COURTROOM_MAP.get("courtroomUid");
            Ftp ftp = new Ftp(courtRoom.getDeviceIp().trim(), courtRoom.getFtpPort(),
                    courtRoom.getFtpUser().trim(), courtRoom.getFtpPsw().trim());
            if (ftp.connect()) {
                ftp.download(ftpFileName, localPath);
                ftp.disconnect();
            }
        } catch (NullPointerException n) {
            logger.error("ERROR: 警告，可能没有找到对应的法庭　" + n.getMessage());
        } catch (IOException e) {
            logger.error("ERROR: ftp下载时出现IO异常　" + e.getMessage());
        }
        logger.info("INFO:笔录文件下载成功");
    }

    private static String getWordText(InputStream inputStream, String filePath) throws IOException {
//        FileInputStream fis = (FileInputStream) inputStream;
        try {
            WordToTextConverter wordToTextConverter = new WordToTextConverter();
//            fis = new FileInputStream(new File(filePath));
            HWPFDocument doc = new HWPFDocument(inputStream);
            HeaderStories hs = new HeaderStories(doc);
            if (hs.getFirstHeaderSubrange() != null)
                wordToTextConverter.processDocumentPart(doc,
                        hs.getFirstHeaderSubrange());
            if (hs.getEvenHeaderSubrange() != null)
                wordToTextConverter.processDocumentPart(doc,
                        hs.getEvenHeaderSubrange());
            if (hs.getOddHeaderSubrange() != null)
                wordToTextConverter.processDocumentPart(doc,
                        hs.getOddHeaderSubrange());
            wordToTextConverter.processDocument(doc);
            wordToTextConverter.processDocumentPart(doc,
                    doc.getMainTextboxRange());
            if (hs.getFirstFooterSubrange() != null)
                wordToTextConverter.processDocumentPart(doc,
                        hs.getFirstFooterSubrange());
            return wordToTextConverter.getText();
        } catch (Exception exc) {
            throw new RuntimeException(exc);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 取得doc本地存储路径
     *
     * @param path
     */
    private String getPath(String path) {
        String[] paths = path.split("/");
        String filepath = "";
        for (int i = 3; i < paths.length; i++) {
            if (!"".equals(filepath)) {
                filepath += "/";
            }
            filepath += paths[i];
        }
        return filepath;
    }
}
